﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SLSYJ.Controllers.DTOs;
using SLSYJ.Core;
using SLSYJ.Data;
using ProjectBase.Core.PersistenceSupport;
using ProjectBase.Core;
using ProjectBase.Web;
using AutoMapper;

namespace SLSYJ.Controllers
{
    public class CategoriesController : Controller
    {
        public CategoriesController()
            : this(new CategoryDao(), new SectorDao(), new TaskDao(), new EmployeeDao())
        {
            
        }

        public CategoriesController(IDao<Category> categoryDao, IDao<Sector> sectorDao, IDao<Task> taskDao, IDao<Employee> employeeDao)
        {
            Check.Require(categoryDao != null, "categoryDao may not be null");
            Check.Require(sectorDao != null, "sectorDao may not be null");
            Check.Require(taskDao != null, "taskDao may not be null");
            Check.Require(employeeDao != null, "employeeDao may not be null");

            this.categoryDao = categoryDao;
            this.sectorDao = sectorDao;
            this.taskDao = taskDao;
            this.employeeDao = employeeDao;
            Mapper.CreateMap<Category, CategoryDTO>();
        }

        public ActionResult GetTaskList(string sidx, string sord, int page, int rows, int categoryId)
        {
            List<Task> tasks = ((TaskDao)taskDao).LoadTaskByCategoryID(categoryId);

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = tasks.Count;
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            List<object> list = GetRowsFromList(tasks);

            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = list
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCategoriesList(string sidx, string sord, int page, int rows)
        {
            List<CategoryDTO> tasks = Mapper.Map<List<Category>, List<CategoryDTO>>(categoryDao.LoadAll());

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = tasks.Count;
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            List<object> list = GetRowsFromList(tasks);

            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = list
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [Transaction]
        public ActionResult Create(string categoryName) {
            Category category = new Category(categoryName);
            category = categoryDao.SaveOrUpdate(category);

            return View("Create", category);
        }

        public ActionResult Detail(int id) {
            Check.Require(id > 0, "Category ID must be > 0");

            Category category = categoryDao.Load(id);
            return View("Detail", category);
        }

        public ActionResult List()
        {
            return View("List");
        }

        public JsonResult UpdateCategorySalary(int categoryId)
        {
            var res = Mapper.Map<Category, CategoryDTO>(categoryDao.Load(categoryId));

            return new JsonResult
            {
                Data = res.GrossSalary,
                ContentEncoding = System.Text.Encoding.UTF8,
                ContentType = "text/html",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        [HttpPost]
        public PartialViewResult ManageSelectedGridItem(string rowid, string action)
        {
            var id = Convert.ToInt32(rowid);
            PartialViewResult retval = PartialView();
            Check.Require(id > 0, "Category ID must be > 0");
            CategoryDTO category = Mapper.Map<Category, CategoryDTO>(categoryDao.Load(id));
            switch (action)
            {
                case "Edit":
                    retval = PartialView("_EditPartial", category);
                    break;
                case "Details":
                    retval = PartialView("_DetailPartial", category);
                    break;
                default:
                    break;
            }
            return retval;
        }

        private static List<object> GetRowsFromList(List<Task> tasks)
        {
            List<object> retval = new List<object>();
            foreach (var task in tasks)
            {
                retval.Add(new
                {
                    id = task.ID,
                    cell = new string[] { 
                        task.Name
                    }
                });
            }
            return retval;
        }

        private static List<object> GetRowsFromList(List<CategoryDTO> categories)
        {
            List<object> retval = new List<object>();
            foreach (var cate in categories)
            {
                retval.Add(new
                {
                    id = cate.ID,
                    cell = new string[] { 
                        cate.Name,
                        String.Format("{0:C}",cate.GrossSalary)
                    }
                });
            }
            return retval;
        }

        private readonly IDao<Employee> employeeDao;
        private readonly IDao<Category> categoryDao;
        private readonly IDao<Sector> sectorDao;
        private readonly IDao<Task> taskDao;
    }
}

